package hy.config;

import com.atomikos.icatch.jta.UserTransactionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.jta.JtaTransactionManager;

import java.util.Properties;

@Configuration
public class MyCfg {
    //uts的目的是为事务管理器中添加一些用户的个人设置
    @Bean(destroyMethod = "close", initMethod = "init",name="uts")
    public UserTransactionManager userTransactionManager() {
        UserTransactionManager uts = new UserTransactionManager();
        uts.setForceShutdown(true);//uts在事务结束后立刻关闭，而不是等待一段时间再关闭
        return uts;
    }

    //真正的事务管理器，参数的设置从uts中获取
    @Bean
    public JtaTransactionManager transactionManager(UserTransactionManager uts) {
        JtaTransactionManager jta = new JtaTransactionManager();
        jta.setTransactionManager(uts);
        return jta;
    }

    //配置数据源工具方法
    private AtomikosDataSourceBean getDs(String dsName, String dbName){
        AtomikosDataSourceBean atom = new AtomikosDataSourceBean();
        atom.setUniqueResourceName(dsName);
        atom.setXaDataSourceClassName(
                "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");
        Properties p = new Properties();
        p.put("URL", "jdbc:mysql://localhost:3306/"+dbName);
        p.put("user", "root");
        p.put("password", "123");
        atom.setXaProperties(p);
        return atom;
    }

    @Bean(name = "ds1")
    public AtomikosDataSourceBean orderDs() {
        return getDs("ds1111","orderDb");
    }

    @Bean(name = "ds2")
    public AtomikosDataSourceBean storeDs() {
        return getDs("ds2222","storeDb");
    }

    //操作数据库使用的jdbc模板,每个模板所使用的数据源不同，通过在形参上添加@qualifier实现
    @Bean("tmpA")
    public JdbcTemplate getTmp1(@Qualifier("ds1") AtomikosDataSourceBean ds){
        System.out.println("ds1========"+ds);
        return new JdbcTemplate(ds);
    }

    @Bean("tmpB")
    public JdbcTemplate getTmp2(@Qualifier("ds2") AtomikosDataSourceBean ds){
        System.out.println("ds2========"+ds);
        return new JdbcTemplate(ds);
    }
}